﻿using System;
using System.Collections.Generic;
using System.Linq;
using DLM.Domain.Model;
using DLM.Domain.Repositories;
using DLM.Infrastructure.UnitOfWork;
using DLM.Infrastructure.Domain;
using Webdiyer.WebControls.Mvc;

namespace DLM.Data.EF.CodeFirst.Repositories
{
    public class OrderRepository : Repository<Order, int>, IOrderRepository
    {
        public OrderRepository(IUnitOfWork unitOfWork)
            : base(unitOfWork)
        {

        }

        public override IEnumerable<Order> FindAll(int pageIndex, int pageSize)
        {
            return this.ActiveContext.Order.AsNoTracking().OrderByDescending(o => o.OrderDate).ToPagedList(pageIndex, pageSize);
        }

        public IEnumerable<Order> FindByAccount(string account,int pageIndex, int pageSize)
        {
            if (string.IsNullOrEmpty(account))
            {
                throw new ArgumentNullException("Account");
            }
            var result = from u in this.ActiveContext.User.AsNoTracking()
                         join o in this.ActiveContext.Order.AsNoTracking()
                         on u.UserID equals o.UserID
                         where u.AccountName == account
                         select o;
            return result.OrderByDescending(o=>o.OrderDate).ToPagedList(pageIndex, pageSize);
            
        }

        public IEnumerable<Order> FindByUser(int userID,int pageIndex, int pageSize)
        {
            var result = from u in this.ActiveContext.User.AsNoTracking()
                         join o in this.ActiveContext.Order.AsNoTracking()
                         on u.UserID equals o.UserID
                         where o.UserID == userID
                         select o;
            return result.OrderByDescending(o => o.OrderDate).ToPagedList(pageIndex, pageSize);

        }

        public Order FindByOrderNo(string orderNo)
        {
            if (string.IsNullOrEmpty(orderNo))
            {
                throw new ArgumentNullException("Order No");
            }
            return this.ActiveContext.Order.AsNoTracking().FirstOrDefault(o => o.OrderNo == orderNo);
        }

        public Order FindByTradeNo(string tradeNo)
        {
            if (string.IsNullOrEmpty(tradeNo))
            {
                throw new ArgumentNullException("Trade No");
            }
            return this.ActiveContext.Order.AsNoTracking().FirstOrDefault(o=>o.TradeNo == tradeNo);
        }

        public new System.Collections.IEnumerator GetEnumerator()
        {
            throw new NotImplementedException();
        }
    }
}
